package com.udaos.modules.sys.controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import com.udaos.common.annotation.SLog;
import com.udaos.common.base.Result;
import com.udaos.common.filter.PrivateFilter;
import com.udaos.models.company.Ud_company;
import com.udaos.models.sys.Sys_unit;
import com.udaos.modules.company.services.UdCompanyService;
import com.udaos.modules.sys.services.SysUnitService;

/**
 * Created by wizzer on 2016/6/24.
 */
@IocBean
@At("/platform/sys/unit")
@Filters({@By(type = PrivateFilter.class)})
public class SysUnitController {
    private static final Log log = Logs.get();
    @Inject
    SysUnitService unitService;
    
    @Inject
    private UdCompanyService companyService;

    @At("")
    @Ok("beetl:/platform/sys/unit/index.html")
    @RequiresAuthentication
    public Object index() {
        return unitService.query(Cnd.where("parentId", "=", "").or("parentId", "is", null).asc("path"));
    }

    @At
    @Ok("beetl:/platform/sys/unit/add.html")
    @RequiresAuthentication
    public Object add(@Param("pid") String pid) {
    	Map<String,Object> map=new HashMap<String,Object>();
    	Cnd cnd=Cnd.NEW();
    	cnd.and("state", "=", 0);
    	cnd.and("delFlag", "=", 0);
    	List<Ud_company> companyList=companyService.query(cnd);
    	map.put("companyList", companyList);
    	if(Strings.isBlank(pid)){
    		map.put("unit", null);
    	}else{
    		Sys_unit unit=unitService.fetch(pid);
    		map.put("unit", unit);
    	}
        return map;
    }

    @At
    @Ok("json")
    @RequiresPermissions("sys.manager.unit.add")
    @SLog(tag = "新建单位", msg = "单位名称:${args[0].name}")
    public Object addDo(@Param("..") Sys_unit unit, @Param("parentId") String parentId, HttpServletRequest req) {
        try {
            unitService.save(unit, parentId);
            return Result.success("操作成功");
        } catch (Exception e) {
            return Result.error("操作失败");
        }
    }

    @At("/child/?")
    @Ok("beetl:/platform/sys/unit/child.html")
    @RequiresAuthentication
    public Object child(String id) {
        return unitService.query(Cnd.where("parentId", "=", id).asc("path"));
    }

    @At("/detail/?")
    @Ok("beetl:/platform/sys/unit/detail.html")
    @RequiresAuthentication
    public Object detail(String id) {
        return unitService.fetch(id);
    }

    @At("/edit/?")
    @Ok("beetl:/platform/sys/unit/edit.html")
    @RequiresAuthentication
    public Object edit(String id, HttpServletRequest req) {
        Sys_unit unit = unitService.fetch(id);
        if (unit != null) {
            req.setAttribute("parentUnit", unitService.fetch(unit.getParentId()));
            if(null != unit.getCompany_id())
            	req.setAttribute("company", companyService.fetch(unit.getCompany_id()));
        }
        return unit;
    }

    @At
    @Ok("json")
    @RequiresPermissions("sys.manager.unit.edit")
    @SLog(tag = "编辑单位", msg = "单位名称:${args[0].name}")
    public Object editDo(@Param("..") Sys_unit unit, @Param("parentId") String parentId, HttpServletRequest req) {
        try {
            unit.setOpBy(Strings.sNull(req.getAttribute("uid")));
            unit.setOpAt((int) (System.currentTimeMillis() / 1000));
            unitService.updateIgnoreNull(unit);
            return Result.success("操作成功");
        } catch (Exception e) {
            return Result.error("操作失败");
        }
    }

    @At("/delete/?")
    @Ok("json")
    @RequiresPermissions("sys.manager.unit.delete")
    @SLog(tag = "删除单位", msg = "单位名称:${args[1].getAttribute('name')}")
    public Object delete(String id, HttpServletRequest req) {
        try {
            Sys_unit unit = unitService.fetch(id);
            req.setAttribute("name", unit.getName());
            if ("0001".equals(unit.getPath())) {
                return Result.error("system.not.allow");
            }
            unitService.deleteAndChild(unit);
            return Result.success("操作成功");
        } catch (Exception e) {
            return Result.error("操作失败");
        }
    }

    @At
    @Ok("json")
    @RequiresAuthentication
    public Object tree(@Param("pid") String pid) {
        List<Sys_unit> list = unitService.query(Cnd.where("parentId", "=", Strings.sBlank(pid)).asc("path"));
        List<Map<String, Object>> tree = new ArrayList<>();
        for (Sys_unit unit : list) {
            Map<String, Object> obj = new HashMap<>();
            obj.put("id", unit.getId());
            obj.put("text", unit.getName());
            obj.put("children", unit.isHasChildren());
            tree.add(obj);
        }
        return tree;
    }
}
